import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class BorrowService {
  constructor(
    private prisma: PrismaService,
  ) {}

  async returnBorrow(
    bookId: number,
  ) {
    const borrows =
      await this.prisma.borrows.findMany(
        {
          where: {
            bookBookId:
              bookId,
          },
        },
      );
    if (borrows.length == 0) {
      return {
        success: false,
        message:
          '该图书未被借阅',
      };
    }
    const studentId =
      borrows[0].studentStuId;
    const stuBorrowList =
      await this.prisma.borrows.findMany(
        {
          where: {
            studentStuId:
              studentId,
          },
        },
      );
    const some =
      stuBorrowList.map(
        (item) => {
          const borrowTime =
            new Date(
              item.JYSJ,
            );
          const now =
            new Date();
          const differ =
            (now.getTime() -
              borrowTime.getTime()) /
            1000;
          if (differ < 3) {
            return {
              success: true,
              data: differ,
            };
          } else {
            return {
              success: false,
              data: differ,
            };
          }
        },
      );
    if (some.length >= 3) {
      return {
        success: false,
        message:
          '您目前有超期罚款，请交款之后还书。',
      };
    } else {
      await this.prisma.borrows.delete(
        {
          where: {
            bookBookId:
              bookId,
          },
        },
      );
      return {
        success: true,
        message: '借阅成功',
      };
    }
  }

  forceReturnBorrow(
    bookId: number,
  ) {
    return this.prisma.borrows.delete(
      {
        where: {
          bookBookId: bookId,
        },
      },
    );
  }
}
